package org.tech4j.common.core.request.param;

import com.google.common.collect.Maps;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.tech4j.common.spi.Join;

import java.util.Arrays;
import java.util.Map;

/**
 * @program: tech4j-common
 * @description:
 * @author: YuKai Fan
 * @create: 2025/3/2 20:05
 **/
@Join
public class CookieParameterData implements ParameterData {

    @Override
    public String builder(String paramName, HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (ArrayUtils.isEmpty(cookies)) {
            return "";
        }
        return Arrays.stream(cookies)
                .filter(cookie -> StringUtils.equals(cookie.getName(), paramName))
                .findFirst()
                .map(Cookie::getValue)
                .orElse("");
    }

    @Override
    public Map<String, Object> builderMap(String paramName, HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (ArrayUtils.isEmpty(cookies)) {
            return null;
        }
        Map<String, Object> map = Maps.newHashMapWithExpectedSize(cookies.length);
         Arrays.stream(cookies)
                .forEach(cookie -> map.put(cookie.getName(), cookie));
         return map;
    }
}
